﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using ZJGIS.Report.model;
using ZJGIS.EngineControl;
using ZJGIS.Framework;
using ZJGIS.ADF.BaseClasses;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;


namespace ZJGIS.Report.button
{
    internal class RoadStatButton : BaseDrawPolygonTool 
    {
        private IElement m_pElement;
        private IFeatureLayer pFeatureLayer;
        private StatisticReport pReport;
        private string strName = "交通线";
        private StatLayer m_pStatLyr = null;
        private DataTable m_pTable=null;
        IApplication m_Application = null;
        IMapControl3 pMapControl = null;

        public RoadStatButton()
        {
            base.m_caption = "道路统计";
            base.m_toolTip = base.m_caption;
        }

        public override void OnCreate(object hook)
        {
            m_Application = hook as IApplication;
            base.OnCreate(hook);
        }

        public override bool Enabled
        {
            get
            {
                
                if ((m_Application as IFramework).IsMapCtrlactive)
                {
                    IEnumLayer layers = (m_Application.Document as IMxDocument).ActiveView.FocusMap.get_Layers(null, true);
                    ILayer layer = layers.Next();
                    while (layer != null)
                    {
                        if (layer is IFeatureLayer)
                        {
                            Marshal.ReleaseComObject(layers);
                            return true;
                        }
                        layer = layers.Next();
                    }
                    Marshal.ReleaseComObject(layers);
                }
                return false;
            }
        }

        public override void OnClick()
        {
            if ((m_Application as IFramework).Tool == this) return;
            base.OnClick();

            if ((m_Application as IFramework).IsMapCtrlactive)
                pMapControl = (m_Application as IFramework).MapControl;
            else
                return;

            if (pMapControl == null || pMapControl.Map.LayerCount == 0) return;

            pFeatureLayer = null;
            m_pStatLyr = StatFactory.GetLayerByID(strName);
            if (m_pStatLyr == null)
            {
                ControlUtility.ShowInfomationMsgbox("尚未找到交通线层，请加载交通线层！");
                return;
            }
            pFeatureLayer = CartoUtility.FindFeatureLayerByName(pMapControl.Map, m_pStatLyr.Value);
            if (pFeatureLayer == null)
            {
                ControlUtility.ShowInfomationMsgbox("尚未找到交通线层，请加载交通线层！");
                return;
            }
            m_cursor = Cursors.Cross;
        }

        public override int Bitmap
        {
            get
            {
                string bitmapResourceName = "ZJGIS.Report.Res." + this.GetType().Name + ".png";
                System.IO.Stream s = GetType().Assembly.GetManifestResourceStream(bitmapResourceName);
                if (s == null) return 0;
                return new Bitmap(s).GetHbitmap().ToInt32(); 
            }
        }
        
        public override void OnDblClick()
        {
            base.OnDblClick();
            if (pFeatureLayer == null) return;
            if (pMapControl == null) return;
            if (m_geom == null || m_geom.IsEmpty) return;
            IPolygon pPolygon = m_geom as IPolygon;
            ITopologicalOperator2 pTopo = pPolygon as ITopologicalOperator2;
            pTopo.IsKnownSimple_2 = false;
            pTopo.Simplify();
            pTopo.IsKnownSimple_2 = true;
            pPolygon.Project(((IGeoDataset)pFeatureLayer.FeatureClass).SpatialReference);

            Application.DoEvents();
            ISpatialFilter pSF = new SpatialFilterClass();
            pSF.Geometry = pPolygon;
            pSF.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            pSF.WhereClause = m_pStatLyr.WhereClause();
            IFeatureCursor pFeatureCursor = pFeatureLayer.FeatureClass .Search(pSF, false);
            int count = pFeatureLayer.FeatureClass.FeatureCount(pSF);
            CreateDatatableByReportfield();

            IFeature pFeature = pFeatureCursor.NextFeature();
            while (pFeature != null)
            {
                AddDataRowByFeature(pFeature, pPolygon);
                pFeature = pFeatureCursor.NextFeature();

            }
            if (m_pTable.Rows.Count == 0)
            {
                ControlUtility.ShowInfomationMsgbox("尚未检索到道路数据，请重试！");
                pMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                return;
            }

            if (pReport == null || pReport.IsDisposed)
            {
                pReport = new StatisticReport();
            }

            pReport.AddConnectDatatable = m_pTable;
            pReport.ReportName = "道路统计报表.rpt";
            if (!pReport.Visible) pReport.Show();
            pReport.RefreshReport();
        }


        private void CreateDatatableByReportfield()
        {
            if(m_pTable ==null)
            {
                m_pTable = new DataTable();
                for (int i = 0; i < m_pStatLyr.ReportFields .Count; i++)
                {
                    ReportField  field=m_pStatLyr.ReportFields[i];
                    DataColumn pColumn = new DataColumn(field.Key);
                    pColumn.DataType = Type.GetType("System." + field.Type);
                    switch (field.Type.ToLower())
                    {
                        case "int":
                        case "int32":
                            pColumn.DefaultValue = 0;
                            break;
                        case "double":
                            pColumn.DefaultValue = 0.000;
                            break;
                        case "string":
                            pColumn.DefaultValue = "";
                            break;
                        default :
                            break;

                    }
                    m_pTable.Columns.Add(pColumn);
                }
            }
            else
            {
                m_pTable.Rows.Clear();
            }
        }

        private void AddDataRowByFeature(IFeature pFeature, IGeometry pGeo)
        {
            if (pFeature == null || pGeo.IsEmpty)  { return; }
            IFields pFields = pFeature.Fields;
            DataRow row = m_pTable.NewRow();
            int idx = -1;
            for (int i = 0; i < m_pStatLyr.ReportFields .Count; i++)
            {
                ReportField  field = m_pStatLyr.ReportFields[i];
                switch (field.Key)
                {
                    case "OID":
                        row[field.Key] = pFeature.OID.ToString();
                        break;
                    case "FCODE":
                        idx = pFields.FindField(field.Value );
                        if (idx > -1)
                        {
                            row[field.Key] = pFeature.get_Value(idx).ToString();
                            row["MGRADE"] = GetRoadType(pFeature.get_Value(idx).ToString());
                        }
                        break;
                    case "NAME":
                    case "TGRADE":
                        idx = pFields.FindField(field.Value );
                        if (idx > -1)
                        {
                            if ((pFeature.get_Value(idx) == null) || Convert.IsDBNull(pFeature.get_Value(idx)))
                                row[field.Key] = "";
                            else
                                row[field.Key] = pFeature.get_Value(idx).ToString();
                        }
                        break;
                    case "WIDTH":
                        idx = pFields.FindField(field.Value);
                        if (idx > -1)
                        {
                            if ((pFeature.get_Value(idx) == null) || Convert.IsDBNull(pFeature.get_Value(idx)))
                                row[field.Key] = 0.000;
                            else
                                row[field.Key] = double.Parse(pFeature.get_Value(idx).ToString());
                        }
                        break;
                    case "LENGTH":
                        IPolyline pl = pFeature.ShapeCopy as IPolyline;
                        row[field.Key] = double.Parse(pl.Length.ToString());
                        ITopologicalOperator pTopo = pGeo as ITopologicalOperator;
                        IPolyline pIntersectPl = pTopo.Intersect(pl, esriGeometryDimension.esriGeometry1Dimension ) as IPolyline ;
                        row["INTERSECTLENGTH"] = double.Parse(pIntersectPl.Length.ToString("F3"));
                        break;

                    default:
                        break;
                }
            }
            m_pTable.Rows.Add(row);

        }

        private string GetRoadType(string strCode)
        {
            if (strCode == null || strCode.Length == 0 || m_pStatLyr.StatCodes.Count ==0)
            {
                return null;
            }
            for (int i = 0; i < m_pStatLyr.StatCodes.Count; i++)
            {
                if (m_pStatLyr.StatCodes[i].Fcode == strCode)
                {
                    return m_pStatLyr.StatCodes[i].Value;
                }
            }
            return null;
        }


    }
}
